package com.googlecode.horncomb.web.spring.context;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SpringRootContextLocatingListener implements
        ServletContextListener
{
    protected final Log logger = LogFactory.getLog(getClass());

    public void contextDestroyed(ServletContextEvent event)
    {
        SpringContextLocator.setRootApplicationContext(null);
    }

    public void contextInitialized(ServletContextEvent event)
    {
        WebApplicationContext ctx = WebApplicationContextUtils
                .getRequiredWebApplicationContext(event.getServletContext());
        if (ctx != null)
        {
            SpringContextLocator.setRootApplicationContext(ctx);
            this.logger
                    .info("成功获取Spring ApplicationContext，并存储到SpringContextLocator: "
                            + ctx);
        }
        else
        {
            this.logger.warn("获取Spring ApplicationContext失败");
        }
    }
}
